package com.heima.leetcode.practice;

import java.util.Arrays;
import java.util.PriorityQueue;

/**
 * @author 勾新杰
 * @version 1.0
 * @description: leetcode 179. 最大数
 * @date 2025/9/16 11:19
 */
public class E179 {

    /**
     * 思路1：用优先级队列
     * 1. 全零判断
     * 2. 创建优先队列
     * 3. 添加数据
     * 4. 获取结果
     * @param nums 数组
     * @return 最大数
     */
    public String largestNumber1(int[] nums) {
        // 1. 全零判断
        boolean allIsZero = true;
        for (int num : nums) {
            if (num != 0) {
                allIsZero = false;
                break;
            }
        }
        if(allIsZero) return "0";
        // 2. 创建优先队列
        PriorityQueue<String> queue = new PriorityQueue<>((a, b) -> {
            char[] aList = (a + b).toCharArray();
            char[] bList = (b + a).toCharArray();
            for(int i = 0; i < aList.length; i++){
                if(aList[i] == bList[i]) continue;
                return bList[i] - aList[i];
            }
            return 0;
        });
        // 3. 添加数据
        for (int num : nums) {
            queue.offer(String.valueOf(num));
        }
        // 4. 获取结果
        StringBuilder builder = new StringBuilder();
        while(!queue.isEmpty()){
            builder.append(queue.poll());
        }
        return builder.toString();
    }

    /**
     * 思路2：直接sort
     * @param nums 数组
     * @return 最大数
     */
    public String largestNumber2(int[] nums) {
        String[] strList = new String[nums.length];
        for (int i = 0; i < nums.length; i++) {
            strList[i] = String.valueOf(nums[i]);
        }
        Arrays.sort(strList, (a, b) -> {
            char[] aList = (a + b).toCharArray();
            char[] bList = (b + a).toCharArray();
            for(int i = 0; i < aList.length; i++){
                if(aList[i] == bList[i]) continue;
                return bList[i] - aList[i];
            }
            return 0;
        });
        if("0".equals(strList[0])) return "0";
        StringBuilder builder = new StringBuilder();
        for (String str : strList) {
            builder.append(str);
        }
        return builder.toString();
    }
}
